import 'dart:ffi';

import 'package:flutter/material.dart';
import 'package:flutter_wanandroid/common/api.dart';
import 'package:flutter_wanandroid/httpUtils/http_util.dart';
import 'package:flutter_wanandroid/pages/CustomDialog.dart';
import 'package:flutter_wanandroid/pages/HomePage.dart';
import 'package:flutter_wanandroid/pages/NaviPage.dart';
import 'package:flutter_wanandroid/pages/TreePage.dart';
import 'package:flutter_wanandroid/pages/about_page.dart';
import 'package:flutter_wanandroid/pages/project_page.dart';
import 'package:flutter_wanandroid/pages/search_page.dart';
import 'package:flutter_wanandroid/pages/theme_dialog.dart';
import 'package:flutter_wanandroid/res/colors.dart';
import 'package:flutter_wanandroid/res/strings.dart';
import 'package:flutter_wanandroid/utils/favoriteProvide.dart';
import 'package:flutter_wanandroid/utils/themeProvide.dart';
import 'package:fluttertoast/fluttertoast.dart';
import 'package:provider/provider.dart';
import 'package:shared_preferences/shared_preferences.dart';

void main() async {
  //用来和flutter引擎交互
  WidgetsFlutterBinding.ensureInitialized();
  int themeIndex = await getTheme();
  runApp(
    MultiProvider(
      providers: [
        //将theme,favorite加到providers中
        ChangeNotifierProvider(create: (ctx) => ThemeProvide()),
        ChangeNotifierProvider(create: (ctx) => FavoriteProvide())
      ],
      child: MyApp(themeIndex),
    ),
  );
}

Future<int> getTheme() async {
  SharedPreferences sp = await SharedPreferences.getInstance();
  int? themeIndex = sp.getInt(YColors.themeIndexKey);
  return themeIndex ?? 0;
}

class MyApp extends StatelessWidget {
  final int themeIndex;

  MyApp(this.themeIndex);

  // This widget is the root of your application.
  @override
  Widget build(BuildContext context) {
    final int themeValue = context.watch<ThemeProvide>().value;
    return MaterialApp(
      title: YStrings.appName,
      theme: ThemeData(
          primaryColor: YColors.themeColor[themeValue]["primaryColor"],
          primaryColorDark: YColors.themeColor[themeValue]["primaryColorDark"],
          hintColor: YColors.themeColor[themeValue]["colorAccent"]),
      home: MyHomePage(title: YStrings.appName),
    );
  }
}

class MyHomePage extends StatefulWidget {
  const MyHomePage({Key? key, required this.title}) : super(key: key);

  final String title;

  @override
  State<MyHomePage> createState() => _MyHomePageState();
}

class _MyHomePageState extends State<MyHomePage> {
  var _pageController = PageController(initialPage: 0);
  int _selectedIndex = 0;
  String title = YStrings.home;

  var page = <Widget>[HomePage(), TreePage(), NaviPage(), ProjectPage()];
  int _counter = 0;

  void _incrementCounter() {
    setState(() {
      _counter++;
    });
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        backgroundColor: Theme.of(context).primaryColor,
        centerTitle: true,
        title: Text(widget.title),
        actions: [
          IconButton(
            onPressed: () {
              Fluttertoast.showToast(msg: "进入搜索页面");
              Navigator.push(context, MaterialPageRoute(builder: (context) => const SearchPage()));
            },
            icon: const Icon(Icons.search),
          ),
        ],
        // leading: Icon(Icons.settings),
      ),
      body: PageView.builder(
        controller: _pageController,
        itemCount: page.length,
        onPageChanged: _pageChange,
        itemBuilder: (context, index) => page.elementAt(_selectedIndex),
      ),
      bottomNavigationBar: BottomNavigationBar(
        items: [
          BottomNavigationBarItem(
            icon: const Icon(Icons.home),
            label: YStrings.home,
          ),
          BottomNavigationBarItem(
            icon: const Icon(Icons.filter_list),
            label: YStrings.tree,
          ),
          BottomNavigationBarItem(
            icon: const Icon(Icons.low_priority),
            label: YStrings.navi,
          ),
          BottomNavigationBarItem(
            icon: const Icon(Icons.apps),
            label: YStrings.project,
          ),
        ],
        //当前选中下表
        currentIndex: _selectedIndex,
        //显示模式
        type: BottomNavigationBarType.fixed,
        //选中颜色
        fixedColor: Theme.of(context).primaryColor,
        //点击事件
        onTap: _onItemTapped,
      ),
      floatingActionButton: FloatingActionButton(
        onPressed: () => _tap(),
        backgroundColor: Theme.of(context).primaryColor,
        tooltip: '点击选中最后一个',
        child: const Icon(
          Icons.add,
          color: Colors.white,
        ),
      ),
      drawer: showDrawer(),
      // This trailing comma makes auto-formatting nicer for build methods.
    );
  }

  Widget showDrawer() {
    return Drawer(
      child: ListView(
        // scrollDirection: Axis.vertical,
        children: [
          UserAccountsDrawerHeader(
            currentAccountPicture: GestureDetector(
              child: const CircleAvatar(
                backgroundImage: AssetImage('lib/res/images/a.jpg'),
                radius: 40,
              ),
            ),
            otherAccountsPictures: [
              IconButton(
                  onPressed: () {},
                  icon: IconButton(
                    icon: const Icon(
                      Icons.star,
                      color: Colors.white,
                    ),
                    onPressed: () {},
                  ))
            ],
            accountName: Text(
              YStrings.proName,
              style: const TextStyle(
                  color: Colors.white,
                  fontSize: 16,
                  fontWeight: FontWeight.bold),
            ),
            accountEmail: Text(
              YStrings.github,
              style: const TextStyle(
                color: Colors.white,
                fontSize: 16,
              ),
            ),
          ),
          ListTile(
            leading: const Icon(Icons.favorite),
            title: const Text("我的收藏"),
            trailing: const Icon(Icons.chevron_right),
            onTap: () {
              Fluttertoast.showToast(msg: "点击我的收藏进入下一页");
              print("点击我的收藏进入下一页");
            },
          ),
          ListTile(
            leading: const Icon(Icons.color_lens),
            title: const Text("切换主题"),
            trailing: const Icon(Icons.chevron_right),
            onTap: () {
              Fluttertoast.showToast(msg: "点击切换主题进入下一页");
              Navigator.pop(context);
              print("点击切换主题进入下一页");
              showDialog(
                  context: context,
                  builder: (context) {
                    return _themeDialog(context);
                  });
            },
          ),
          ListTile(
            leading: const Icon(Icons.share),
            title: const Text("我要分享"),
            trailing: const Icon(Icons.chevron_right),
            onTap: () {
              Fluttertoast.showToast(msg: "点击我要分享进入下一页");
              print("点击我要分享进入下一页");
            },
          ),
          ListTile(
            leading: const Icon(Icons.info_outline),
            title: const Text("关于项目"),
            trailing: const Icon(Icons.chevron_right),
            onTap: () {
              Fluttertoast.showToast(msg: "点击关于项目进入下一页");
              print("点击关于项目进入下一页");
              Navigator.pop(context);
              Navigator.push(
                context,
                MaterialPageRoute(
                  builder: (context) => const AboutPage(),
                ),
              );
            },
          ),
          const Divider(),
          ListTile(
            leading: const Icon(Icons.block),
            title: const Text("退出"),
            trailing: const Icon(Icons.chevron_right),
            onTap: () {
              Fluttertoast.showToast(msg: "点击退出进入下一页");
              print("点击退出进入下一页");
              //关闭drawer
              Navigator.of(context).pop();
              showDialog(
                  context: context,
                  builder: (context) {
                    return _alertDialog();
                  });
            },
          ),
        ],
      ),
    );
    // return Drawer(
    //   child: ListView(
    //     scrollDirection: Axis.vertical,
    //     children: [
    //       Container(
    //         height: 200,
    //         width: MediaQuery.of(context).size.width,
    //         decoration: BoxDecoration(color: Theme.of(context).primaryColor),
    //         child: Column(
    //           children: [
    //             Row(
    //               mainAxisAlignment: MainAxisAlignment.spaceBetween,
    //               children: [
    //                 // UserAccountsDrawerHeader(
    //                 //
    //                 // )
    //                 const Padding(
    //                   padding: EdgeInsets.only(top: 40, left: 20),
    //                   child: CircleAvatar(
    //                     backgroundImage: AssetImage("lib/res/images/a.jpg"),
    //                     radius: 40,
    //                   ),
    //                 ),
    //                 Padding(
    //                   padding: const EdgeInsets.only(right: 20),
    //                   child: IconButton(
    //                     onPressed: () {
    //                       print("点击收藏");
    //                       Fluttertoast.showToast(msg: "点击收藏");
    //                     },
    //                     icon: const Icon(
    //                       Icons.star,
    //                       color: Colors.white,
    //                     ),
    //                   ),
    //                 ),
    //               ],
    //             ),
    //             const SizedBox(
    //               height: 20,
    //             ),
    //             Container(
    //               padding: EdgeInsets.only(left: 20),
    //               alignment: Alignment.centerLeft,
    //               child: const Text(
    //                 "flutter_wanandroid",
    //                 style: TextStyle(
    //                     fontSize: 16,
    //                     fontWeight: FontWeight.bold,
    //                     color: Colors.white),
    //               ),
    //             ),
    //             Container(
    //               alignment: Alignment.centerLeft,
    //               padding: const EdgeInsets.only(left: 20, top: 10),
    //               child: const Text(
    //                 "www.wanandroid.com",
    //                 style: TextStyle(color: Colors.white, fontSize: 16),
    //               ),
    //             )
    //           ],
    //         ),
    //       ),
    //       const SizedBox(
    //         height: 40,
    //       ),
    //       GestureDetector(
    //         child: Container(
    //           padding: const EdgeInsets.symmetric(horizontal: 10),
    //           child: Row(
    //             children: [
    //               IconButton(
    //                 onPressed: () {
    //                   print("点击收藏图标");
    //                 },
    //                 icon: const Icon(Icons.favorite_border),
    //               ),
    //               const Expanded(
    //                 child: Text("我的收藏"),
    //               ),
    //               IconButton(
    //                 onPressed: () {},
    //                 icon: const Icon(Icons.chevron_right),
    //               ),
    //             ],
    //           ),
    //         ),
    //         onTap: () {
    //           print("点击我的收藏");
    //           Fluttertoast.showToast(msg: "点击我的收藏");
    //         },
    //       )
    //     ],
    //   ),
    // );
  }

  Widget _alertDialog() {
    return AlertDialog(
      title: const Text("提示"),
      content: const Text("确认退出吗？"),
      actions: [
        TextButton(
          onPressed: () {
            Navigator.pop(context, "取消");
          },
          child: const Text(
            "取消",
            style: TextStyle(
              color: Colors.grey,
            ),
          ),
        ),
        TextButton(
          onPressed: () {
            //退出
            HttpUtil().get(Api.LOGOUT);
            Navigator.of(context).pop();
          },
          child: Text(
            "确定",
            style: TextStyle(color: Theme.of(context).primaryColor),
          ),
        ),
      ],
    );
  }

  Widget _themeDialog(BuildContext context) {
    // return ThemeDialog(title: "主题颜色", content: "", confirmCallBack: () {}, cancelCallBack: () {});
    // return CustomDialog(title: "主题颜色", content: "", dialogType: DialogType.alert, confirmCallBack: () {}, cancelCallBack: () {});
    return AlertDialog(
      title: const Text("主题颜色"),
      content: SingleChildScrollView(
        child: Container(
          //包含ListView要指定宽高
          width: MediaQuery.of(context).size.width * 0.9,
          height: MediaQuery.of(context).size.height * 0.5,
          child: ListView.builder(
              itemCount: YColors.themeColor.length,
              itemBuilder: (context, i) {
                return GestureDetector(
                  child: Container(
                    padding: EdgeInsets.all(20.0),
                    margin: EdgeInsets.only(bottom: 15),
                    color: YColors.themeColor[i]["primaryColor"],
                  ),
                  onTap: () async {
                    context.read<ThemeProvide>().changeTheme(i);
                    //存储主题下标
                    SharedPreferences sp =
                        await SharedPreferences.getInstance();
                    sp.setInt(YColors.themeIndexKey, i);
                    Navigator.of(context).pop();
                  },
                );
              }),
        ),
      ),
      actions: [
        TextButton(
          onPressed: () {
            Navigator.pop(context);
          },
          child: Text(
            "关闭",
            style: TextStyle(
              color: Theme.of(context).primaryColor,
            ),
          ),
        )
      ],
    );
  }

  //自定义Alert弹窗
  Widget customAlertDialog(BuildContext context) {
    return Container(
      height: 100,
      margin: EdgeInsets.only(left: 40, right: 40),
      color: Colors.white,
      child: Column(
        children: [
          Padding(
            padding: EdgeInsets.all(20),
            child: Stack(
              children: [
                Align(
                  child: Text(
                    title,
                    style: TextStyle(fontSize: 20, color: Color(0xFF2D2D2D)),
                  ),
                ),
                // Align(
                //   alignment: Alignment.centerRight,
                //   child: InkWell(
                //     child: Icon(Icons.close),
                //     onTap: () {
                //       Navigator.of(context).pop();
                //     },
                //   ),
                // ),
              ],
            ),
          ),
          Divider(),
          // Container(
          //   width: double.infinity,
          //   margin: EdgeInsets.all(10),
          //   child: Text(
          //     "content",
          //     textAlign: TextAlign.left,
          //   ),
          // )
        ],
      ),
    );
  }

  void _tap() {
    Fluttertoast.showToast(
      msg: '点击到最后一页',
      gravity: ToastGravity.CENTER,
      textColor: Colors.white,
      backgroundColor: Theme.of(context).primaryColor,
      fontSize: 16,
      toastLength: Toast.LENGTH_SHORT,
      timeInSecForIosWeb: 1,
    );
    _onItemTapped(page.length - 1);
  }

  void _onItemTapped(int index) {
    //bottomNavigationBar 和 PageView 关联
    _pageController.animateToPage(index,
        duration: const Duration(milliseconds: 300), curve: Curves.ease);
  }

  void _pageChange(int index) {
    setState(() {
      _selectedIndex = index;
      switch (index) {
        case 0:
          title = YStrings.home;
          break;
        case 1:
          title = YStrings.tree;
          break;
        case 3:
          title = YStrings.navi;
          break;
        case 4:
          title = YStrings.project;
          break;
      }
    });
  }
}
